<template>
  <div class="app-container own-app-container">
    <el-main>
      <el-row :gutter="20" type="flex" align="center" class="margin-bottom">
        <el-col>
          <el-button type="primary" size="mini" @click.native="showAdd()">新增
          </el-button>
        </el-col>
      </el-row>
      <el-table size="mini" stripe ref="multipleTable" :data="tableData" tooltip-effect="dark" v-loading="tabLoading"
        style="width: 100%" :row-class-name="tableRowClassName" border @selection-change="handleSelectionChange"
        :default-sort="{prop: 'date', order: 'descending'}" highlight-current-row row-key="id">
        <el-table-column type="index" label="序号" width="50" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" width="200" header-align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="emergency" label="紧急程度" width="120" show-overflow-tooltip sortable='custom'
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.emergency==1">紧急</span>
            <span v-if="scope.row.emergency==2">较紧急</span>
            <span v-if="scope.row.emergency==3">普通</span>
            <span v-if="scope.row.emergency==4">不紧急</span>
          </template>
        </el-table-column>
        <el-table-column prop="important" label="重要程度" width="120" show-overflow-tooltip sortable='custom'
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.important==1">重要</span>
            <span v-if="scope.row.important==2">较重要</span>
            <span v-if="scope.row.important==3">普通</span>
            <span v-if="scope.row.important==4">不重要</span>
          </template>
        </el-table-column>
        <el-table-column label="截止时间" prop="deadline" width="140" header-align="center" align="center"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="use_tip" label="开启提醒" width="120" show-overflow-tooltip sortable='custom' align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.use_tip==0">否</span>
            <span v-if="scope.row.use_tip==1">是</span>
          </template>
        </el-table-column>
        <el-table-column prop="use_continue_tip" label="开启持续提醒" width="120" show-overflow-tooltip sortable='custom'
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.use_continue_tip==0">否</span>
            <span v-if="scope.row.use_continue_tip==1">是</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" prop="cur_status" width="120" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.cur_status==0">关闭</span>
            <span v-if="scope.row.cur_status==1">执行中</span>
             <span v-if="scope.row.cur_status==2">完成</span>
          </template>
        </el-table-column>
        <el-table-column label="关闭时间" prop="off_at" width="160" header-align="center" align="center" />
        <el-table-column label="完成时间" prop="complete_at" width="160" header-align="center" align="center" />
        <el-table-column label="操作" min-width="100" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation">
              <el-button-group>
                <el-button type="primary" icon="el-icon-document-checked" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                <el-button type="warning" icon="el-icon-document-checked" size="mini" @click.native="off(scope.row.id)">关闭</el-button>
                <el-button type="success" icon="el-icon-document-checked" size="mini" @click.native="complete(scope.row.id)">完成</el-button>
                <el-button type="danger" icon="el-icon-document-checked" size="mini" @click.native="del(scope.row.id);">删除</el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页数据 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="current"
        :page-sizes="[10, 20, 50]" :page-size="listParams.page_size" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </el-main>

    <el-dialog :close-on-click-modal="false" :title="(cuForm.id?'编辑':'新增')" center :visible.sync="dialogCU" width="80%"
      @close="dialogCUClose('cuForm')">
      <el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" label-width="120px" center>
        <el-row class="row-bg">
          <el-col :span="10">
            <el-form-item label="任务标题" prop="title">
              <el-col :span="24">
                <el-input clearable v-model.trim="cuForm.title" placeholder="请输入标题" />
              </el-col>
            </el-form-item>
            <el-form-item label="紧急程度" prop="emergency">
              <el-select clearable filterable value-key="id" v-model="cuForm.emergency" placeholder="请选择紧急程度"
                style="width:100%">
                <el-option v-for="item in emergencyList" :key="item.id" :label="item.name" :value="item.id" >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="截止时间" prop="deadline">
              <el-col :span="24">
                <el-date-picker v-model.trim="cuForm.deadline" type="datetime" placeholder="请选择截止日期"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="是否开启提醒" prop="use_tip">
              <el-col :span="24">
                <el-radio-group @change="changeUseTip" v-model="cuForm.use_tip">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item v-if="is_use_tip == 1" label="首次提醒提前" prop="prev_tip_gap_num">
              <el-col :span="24">
                <el-input clearable v-model.trim="cuForm.prev_tip_gap_num" placeholder="首次提醒提前的多少时间(数字)" />
              </el-col>
            </el-form-item>
            <el-form-item v-if="is_use_tip == 1" label="首次提醒提前" prop="prev_tip_gap_unit">
              <el-col :span="24">
                <el-select clearable v-model.trim="cuForm.prev_tip_gap_unit" placeholder="首次提醒提前的单位">
                  <el-option label="分钟" :value="1"></el-option>
                  <el-option label="小时" :value="2"></el-option>
                  <el-option label="天" :value="3"></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-form-item label="执行人" prop="operator_ids">
              <el-col :span="24">
                <el-select clearable collapse-tags v-model="cuForm.operator_ids" placeholder="请选择执行人" style="width:100%"
                  value-key="id" multiple >
                  <el-option v-for="item in opereators" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="重要程度" prop="important">
              <el-select clearable filterable value-key="id" v-model="cuForm.important" placeholder="请选择重要程度"
                style="width:100%">
                <el-option v-for="item in importantList" :key="item.id" :label="item.name" :value="item.id" >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否持续提醒" prop="use_continue_tip">
              <el-col :span="24">
                <el-radio-group @change="changeUseContinueTip" v-model="cuForm.use_continue_tip">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item v-if="is_use_continue_tip == 1" label="持续提醒间隔" prop="continue_tip_gap_num">
              <el-col :span="24">
                <el-input clearable v-model.trim="cuForm.continue_tip_gap_num" placeholder="持续提醒间隔（数字）" />
              </el-col>
            </el-form-item>
            <el-form-item v-if="is_use_continue_tip == 1" label="持续提醒间隔" prop="continue_tip_gap_unit">
              <el-col :span="24">
                <el-select clearable v-model="cuForm.continue_tip_gap_unit" placeholder="持续提醒间隔单位">
                  <el-option label="分钟" :value="1"></el-option>
                  <el-option label="小时" :value="2"></el-option>
                  <el-option label="天" :value="3"></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述" prop="desp">
          <el-col :span="22">
            <quill-editor-own  v-model="cuForm.desp"></quill-editor-own>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCU=false">取 消</el-button>
        <el-button type="primary" @click.native="onSubmit(cuForm.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    my_send_list as list,
    addMission,
    editMission,
    offMission,
    completeMission,
    deleteMission
  } from '@/api/personnel/mission'
  import {
    Message
  } from 'element-ui';
  // 富文本
  import QuillEditorOwn from '@/components/QuillEditorOwn'
  export default {
    components: {
      QuillEditorOwn
    },
    name: 'PersonalMySendList',
    // beforeRouteLeave(to, from, next) {
    //   this.$destroy();
    //   next();
    // },

    data() {

      return {
        // list table
        tableData: [], // 列表数据
        selectIds: [], // 多选选项id
        emergencyList: [
          {id:1, name:'紧急'},
          {id:2, name:'较紧急'},
          {id:3, name:'普通'},
          {id:4, name:'不紧急'}
        ],
        importantList: [
          {id:1, name:'重要'},
          {id:2, name:'较重要'},
          {id:3, name:'普通'},
          {id:4, name:'不重要'}
        ],
        selectIds: [], // 多选选项id
        tabLoading: false,
        total: null, // 总页数
        current: 1, // 当前页

        is_use_tip: 0, // 是否开启提醒
        is_use_continue_tip: 0, // 是否开启持续提醒
        tabLoading: true,
        // CU dialog
        dialogCULoading: false,
        dialogCU: false,
        opereators: [
          {id:1, name:'超管'},
          {id:2, name:'张三'},
          {id:3, name:'李四'}
        ],
        cuForm: {
          id: null,
          title: null,
          desp: null,
          emergency: null,
          important: null,
          deadline: null,
          use_tip: 0,
          prev_tip_gap_num: null,
          prev_tip_gap_unit: null,
          use_continue_tip: 0,
          continue_tip_gap_num: null,
          continue_tip_gap_unit: null,
          operator_ids: null
        },
        cuRules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          important: [{
            required: true,
            message: "请选择重要程度",
            trigger: "change"
          }],
          emergency: [{
            required: true,
            message: '请选择紧急程度',
            trigger: 'change'
          }],
          deadline: [{
            required: true,
            message: '请选择截止日期',
            trigger: 'change'
          }],
          operator_ids: [{
            required: true,
            message: '请选择执行人',
            trigger: 'change'
          }]
        },

        listParams: {
          page: 1,
          page_size: 10
        }, // list参数
        searchForm: {

        },
        loading: null,
      }
    },
    mounted() {
      this.getList()
    },
    created() {
      // this.$store.dispatch('flow/getFlowObj');
    },
    methods: {
      changeUseTip(e) {


        if (e == 1) {
          this.is_use_tip = 1
          this.cuForm.prev_tip_gap_num = null
          this.cuForm.prev_tip_gap_unit = null
        }else {
          if(this.cuForm.use_continue_tip == 1){
            this.is_use_tip = 1
            this.cuForm.use_tip = 1
            this.$message.error('请先关闭持续提醒')
          } else {
            this.is_use_tip = 0
          }
        }
      },
      changeUseContinueTip(e) {
        if (e == 0) {
          this.is_use_continue_tip = 0
          this.cuForm.continue_tip_gap_num = null
          this.cuForm.continue_tip_gap_unit = null
        } else {
          if (this.cuForm.use_tip == 0) {
            this.$message.error('请先开启提醒')
            this.cuForm.use_continue_tip = 0
            this.is_use_continue_tip = 0
          } else {
            this.is_use_continue_tip = 1
          }
        }
      },
      showAdd() {
        const _this = this
        _this.cuForm = Object.assign({}, _this.resetForm())
        _this.is_use_continue_tip = 0
        _this.is_use_tip = 0
        _this.$nextTick(() => {
          _this.dialogCU = true
          _this.$refs['cuForm'] && _this.$refs['cuForm'].clearValidate()
          _this.dialogCULoading = false
        })
      },
      showEdit(row){
        this.cuForm = Object.assign({}, row)
        this.is_use_tip = 0
        this.is_use_continue_tip = 0
        if(row.use_tip == 1){
          this.is_use_tip = 1
        }
        if(row.use_continue_tip == 1){
          this.is_use_continue_tip = 1
        }
        this.dialogCU = true
        this.dialogCULoading = false
      },
      del(id) {
        this.$confirm('确认要删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          })
          .then(() => {
            let ids = [id];
            deleteMission(ids).then(res => {
              let {
                code,
                date,
                message
              } = res;
              this.getList();
              Message({
                message,
                type: "success",
                duration: 1000
              });
            });
          }).catch()
      },
      off(id) {
        this.$confirm('确认要关闭?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          })
          .then(() => {
            let ids = [id];
            offMission(ids).then(res => {
              let {
                code,
                date,
                message
              } = res;
              this.getList();
              Message({
                message,
                type: "success",
                duration: 1000
              });
            });
          }).catch()
      },
      complete(id) {
        this.$confirm('确认要完成?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          })
          .then(() => {
            let ids = [id];
            completeMission(ids).then(res => {
              let {
                code,
                date,
                message
              } = res;
              this.getList();
              Message({
                message,
                type: "success",
                duration: 1000
              });
            });
          }).catch()
      },
      // 关闭弹窗
      dialogCUClose(formName) {
        switch (formName) {
          case 'cuForm':
            this.$refs['cuForm'].clearValidate()
            break
        }
      },

      // 提交数据 增、改
      onSubmit(id) {
        // 表单校验
        this.$refs.cuForm.validate(valid => {
          // ~ 校验通过
          if (valid) {
            var obj = Object.assign({}, this.cuForm)

            if(obj.use_tip == 1){
              if(obj.prev_tip_gap_num == null || obj.prev_tip_gap_num == ''){
                this.$message.error('请输入首次提醒需要提前的时间')
                return false
              }
              if(obj.prev_tip_gap_unit == null || obj.prev_tip_gap_unit == ''){
                this.$message.error('请选择首次提醒提前的时间单位')
                return false
              }
            }

            if(obj.use_continue_tip == 1){
              if(obj.continue_tip_gap_num == null || obj.continue_tip_gap_num == ''){
                this.$message.error('请输入持续提醒需要的间隔时间')
                return false
              }
              if(obj.continue_tip_gap_unit == null || obj.continue_tip_gap_unit == ''){
                this.$message.error('请输入持续提醒的间隔时间单位')
                return false
              }
            }

            console.log("obj", obj)
            // return false

            // 显示loading
            this.dialogCULoading = true;

            // ~~ 修改
            if (id) {
              this.onEdit(obj);
            } else {
              // ~~ 添加
              delete obj.id
              this.onAdd(obj);
            }
          } else {
            // ~ 不通过
            return false;
          }
        });
      },
    // 添加
    onAdd(obj) {
      return addMission(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },

    // 编辑
    onEdit(obj) {
      return editMission(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },
      getList() {
        this.tabLoading = true
        return list(this.listParams)
          .then(res => {
            let {
              data: {
                records,
                total
              }
            } = res;

            this.tableData = records.map(item => {
              item.operator_ids = (item.operators_id ? (item.operators_id.split(',').map(item => parseInt(item))) : null)
              return item
            });
            this.total = total;
            this.tabLoading = false;
          })
          .catch(() => {
            this.tabLoading = false
          })
      },

      resetForm() {
        return {
          id: null,
          title: null,
          desp: null,
          emergency: null,
          important: null,
          deadline: null,
          use_tip: 0,
          prev_tip_gap_num: null,
          prev_tip_gap_unit: null,
          use_continue_tip: 0,
          continue_tip_gap_num: null,
          continue_tip_gap_unit: null,
          operator_ids: null,
        }
      },

      // 表单多选
      handleSelectionChange(val) {
        this.selectIds = val.map(item => item.id)
      },
      // 分页 -pageSize改变
      handleSizeChange(val) {
        this.listParams.page_size = val
        this.getList()
      },
      // 分页 -pageNum改变
      handleCurrentChange(val) {
        this.listParams.page = val
        this.getList()
      },
      //带状态表格
      tableRowClassName({
        row
      }) {
        return "";
      },

    }
  }
</script>

<style>
</style>
